package com.weijianhuawen.wjblog.admin.event.subscriber;

import com.weijianhuawen.wjblog.admin.event.PublishArticleEvent;
import com.weijianhuawen.wjblog.admin.service.AdminStatisticsService;
import com.weijianhuawen.wjblog.common.domain.dos.ArticleCategoryRelDo;
import com.weijianhuawen.wjblog.common.domain.dos.ArticleTagRelDo;
import com.weijianhuawen.wjblog.common.domain.mapper.ArticleCategoryRelMapper;
import com.weijianhuawen.wjblog.common.domain.mapper.ArticleTagRelMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description:
 * @date: 2024-11-08 13:43
 */
@Component
@Slf4j
public class PublishArticleStatisticsSubscriber implements ApplicationListener<PublishArticleEvent> {
    @Resource
    private ArticleCategoryRelMapper articleCategoryRelMapper;
    @Resource
    private ArticleTagRelMapper articleTagRelMapper;
    @Autowired
    private AdminStatisticsService adminStatisticsService;
    @Override
    public void onApplicationEvent(PublishArticleEvent event) {
        // 消费 删除文章 事件
        Long articleId = event.getArticleId();
        // 获取当前线程名称
        String threadName = Thread.currentThread().getName();

        log.info("【发布文章事件订阅者 统计】 线程：{}开始处理订阅者行为！", threadName );
        log.info("【发布文章事件订阅者 统计】 开始消费！处理文章id：{}", articleId);
        // 查询文章关联分类记录
        ArticleCategoryRelDo articleCategoryRelDo = articleCategoryRelMapper.selectByArticleId(articleId);
        // 更新对应分类id 下的文章数量
        if (Objects.nonNull(articleCategoryRelDo))
            adminStatisticsService.statisticsOneCategoryArticleTotal(articleCategoryRelDo.getCategoryId());

        // 查询文章关联标签记录
        List<ArticleTagRelDo> articleTagRelDos = articleTagRelMapper.selectByArticleId(articleId);
        if (!CollectionUtils.isEmpty(articleTagRelDos)) {
            // 获取需要更新标签的id
            List<Long> tagIds = articleTagRelDos
                    .stream()
                    .map(ArticleTagRelDo::getTagId)
                    .collect(Collectors.toList());
            // 更新tagid 下的文章总数记录
            adminStatisticsService.statisticsSomeTagsArticleTotal(tagIds);
        }
        log.info("【发布文章事件订阅者 统计】 完成！");
    }
}
